// 添加当前学生打卡记录
const cloud = require('wx-server-sdk')

cloud.init({
	env: cloud.DYNAMIC_CURRENT_ENV
})
const db = cloud.database();
const taskrecordCollection = db.collection('taskrecord')
const TcbRouter = require('tcb-router');

// 云函数入口函数
exports.main = async (event, context) => {
	let app = new TcbRouter({event})
	const {OPENID} = cloud.getWXContext()
	// 判断当前是否有打卡
	app.router('whether',async (ctx,next)=>{
		ctx.body = await taskrecordCollection
		.where({
			OPENID,
			state: 0
		}).get()
	})
	// 创建当前打卡记录
	app.router('save',async (ctx,next)=>{
		let {startTime=Date.now(),endTime=null,taskid,time=null,name,img} = event;
		let task = await taskrecordCollection
			.where({
				taskid,
				OPENID,
				state: 0
			}).get()
		if(task.data.length>0){
			ctx.body = {
				msg: "当前已经有在进行中的打卡"
			}
			return 
		}
		ctx.body = taskrecordCollection.add({
			data: {
				endTime,
				startTime,
				taskid,
				OPENID,
				time,
				state: 0,
				openid: OPENID,
				name,img
			}
		})
	})
	
	// 结束时间
	app.router('end',async (ctx,next)=>{
		let {taskid} = event;
		let task = await taskrecordCollection
			.where({
				taskid: taskid
			})
			.orderBy('startTime','desc')
			.get()
		ctx.body = await taskrecordCollection
			.where({
				taskid: taskid,
				_id: task.data[0]._id
			})
			.update({
				data: {
					endTime: Date.now(),
					state: 1,
					// time 分钟
					time: Math.floor((Date.now() - task.data[0].startTime)/1000/60)
				}
			})
			.then(res=>res);
	})
	app.router('squadidList',async (ctx,next)=>{
		let {taskid} = event;
		ctx.body = await taskrecordCollection
		.where({
			taskid
		})
		.get()
		.then(res=>res);
	})
	app.router('list',async (ctx,next)=>{
		let {pageNum=1,pageSize=1000,squadid} = event;
		ctx.body = await taskrecordCollection
			.where({
				squadid
			})
			.skip((pageNum-1)*pageSize)
			.limit(pageSize)
			.orderBy('createTime','desc')
			.get()
			.then(res=>res);
	})
	return app.serve()
}